package cn.turing.firecontrol.datahandler.modbus.task;

import cn.turing.firecontrol.datahandler.modbus.entity.ModbusRTUOp;
import cn.turing.firecontrol.device.entity.DeviceSensor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;


import java.util.Date;

/**
 * @Classname MyTask
 * @Description 定时发送告警
 * @Version 1.0.0
 * @Date 2022/6/27 17:47
 * @Created by wupenghao
 */
@Component
@Slf4j
@EnableScheduling  //开启定时任务
public class MyTask {

    ModbusRTUOp modbusRTUOp=new ModbusRTUOp();
    public void continueRead() throws Exception {
        //1.初始化连接处理
        //虚拟设备地理信息
        DeviceSensor deviceSensor = new DeviceSensor();
        deviceSensor.setBuildingId(111);
        deviceSensor.setChannelId(1);
        deviceSensor.setSensorTypeId(1);
        deviceSensor.setCdId(111);
        deviceSensor.setFieldStatus("1");
        deviceSensor.setStatus("2");
        deviceSensor.setSensorNo("QVFTRVTMUAOP");
        deviceSensor.setFloor(1);
        deviceSensor.setPositionDescription("展厅");
        deviceSensor.setPositionSign(null);
        deviceSensor.setDelFlag("0");
        deviceSensor.setCrtUserName("admin");
        deviceSensor.setCrtUserId("1");
        deviceSensor.setCrtTime(new Date());
        deviceSensor.setUpdUserName("admin");
        deviceSensor.setUpdUserId("1");
        deviceSensor.setUpdTime(new Date());
        deviceSensor.setDepartId(null);
        deviceSensor.setTenantId("ac88ceb386aa4231b09bf472cb937c24");
        deviceSensor.setStatusTime(new Date());
        deviceSensor.setHydrantId(null);
        //初始化
        ModbusRTUOp.init();
        while (true) {
            try {
                short[] data = ModbusRTUOp.batchReadHoldingRegisters(ModbusRTUOp.SLAVE_ADDRESS, 0x0B, 1);  //index从0开始，对应100
                System.out.println("" + data[0]);
                //设置Status
                if (data[0] <= 5){
                    deviceSensor.setStatus("2");  //正常
                    log.info("正常");
                }else {
                    deviceSensor.setStatus("1");  //报警
                    log.info("报警");
                }
            } catch (Exception ex) {
                deviceSensor.setStatus("3");  //故障
                log.info("故障");
                System.out.println(ex.getMessage());
            } finally {
                //插入数据库
                /*deviceSensorDao.insert(deviceSensor);*/
            }
            //下一阶段
            Thread.sleep(100);
        }
    }

    /**
     *  定时检查设备状态
     *  因为 没有硬件会报错
     * @throws Exception
     */
/*    @Scheduled(cron = "0 /1 * * * ?")*/
    public void test() throws Exception {
        log.info("开始定时任务");
        this.continueRead();
    }

}
